<template>
  <div class="storage-statistics">
    <!-- 页面标题 -->
    <van-nav-bar title="入库统计" left-arrow @click-left="$router.back()" />

    <!-- 搜索条件 -->
    <van-form @submit="loadData">
      <van-cell-group inset>
        <van-field
          v-model="searchForm.startDate"
          name="startDate"
          label="开始日期"
          placeholder="请选择开始日期"
          readonly
          @click="showStartDatePicker = true"
        />
        <van-field
          v-model="searchForm.endDate"
          name="endDate"
          label="结束日期"
          placeholder="请选择结束日期"
          readonly
          @click="showEndDatePicker = true"
        />
        <van-field
          v-model="searchForm.dataType"
          name="dataType"
          label="数据类型"
          placeholder="请选择数据类型"
          readonly
          @click="showDataTypePicker = true"
        />
        <van-field
          v-model="searchForm.storageStatus"
          name="storageStatus"
          label="入库状态"
          placeholder="请选择入库状态"
          readonly
          @click="showStatusPicker = true"
        />
      </van-cell-group>

      <div style="margin: 16px;">
        <van-row gutter="8">
          <van-col span="8">
            <van-button round block type="primary" native-type="submit">
              查询
            </van-button>
          </van-col>
          <van-col span="8">
            <van-button round block @click="resetSearch">
              重置
            </van-button>
          </van-col>
          <van-col span="8">
            <van-button round block @click="exportData">
              导出
            </van-button>
          </van-col>
        </van-row>
      </div>
    </van-form>

    <!-- 统计概览 -->
    <van-cell-group inset title="统计概览" v-if="overview">
      <van-cell title="总记录数" :value="overview.totalRecords" />
      <van-cell title="成功记录" :value="overview.successCount" />
      <van-cell title="失败记录" :value="overview.failedCount" />
      <van-cell title="人民币总金额" :value="formatAmount(overview.totalRmbAmount)" />
      <van-cell title="美元总金额" :value="formatAmount(overview.totalUsdAmount)" />
    </van-cell-group>

    <!-- 数据列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell-group inset v-for="item in list" :key="item.id">
          <van-cell :title="item.dataType" :label="item.clearanceDate">
            <template #right-icon>
              <van-tag :type="item.storageStatus === 'SUCCESS' ? 'success' : 'danger'">
                {{ item.storageStatusText }}
              </van-tag>
            </template>
          </van-cell>

          <van-cell title="人民币金额" :value="formatAmount(item.rmbAmount)" />
          <van-cell title="美元金额" :value="formatAmount(item.usdAmount)" />
          <van-cell title="金额同比" :value="item.yearOnYearGrowthText" />
          <van-cell title="金额环比" :value="item.monthOnMonthGrowthText" />
          <van-cell title="记录条数" :value="item.recordCount" />
          <van-cell title="入库时间" :value="item.storageTime" />

          <van-cell
            v-if="item.failureReason"
            title="失败原因"
            :value="item.failureReason"
          />
        </van-cell-group>
      </van-list>
    </van-pull-refresh>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showStartDatePicker" position="bottom">
      <van-date-picker
        v-model="startDate"
        @confirm="onStartDateConfirm"
        @cancel="showStartDatePicker = false"
      />
    </van-popup>

    <van-popup v-model:show="showEndDatePicker" position="bottom">
      <van-date-picker
        v-model="endDate"
        @confirm="onEndDateConfirm"
        @cancel="showEndDatePicker = false"
      />
    </van-popup>

    <!-- 数据类型选择器 -->
    <van-popup v-model:show="showDataTypePicker" position="bottom">
      <van-picker
        :columns="dataTypeOptions"
        @confirm="onDataTypeConfirm"
        @cancel="showDataTypePicker = false"
      />
    </van-popup>

    <!-- 状态选择器 -->
    <van-popup v-model:show="showStatusPicker" position="bottom">
      <van-picker
        :columns="statusOptions"
        @confirm="onStatusConfirm"
        @cancel="showStatusPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { storageStatisticsApi } from '@/api/datacollection'

// 响应式数据
const list = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const overview = ref(null)

// 分页参数
const pageNo = ref(1)
const pageSize = 20

// 搜索表单
const searchForm = reactive({
  startDate: '',
  endDate: '',
  dataType: '',
  storageStatus: ''
})

// 选择器显示状态
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)
const showDataTypePicker = ref(false)
const showStatusPicker = ref(false)

// 日期选择器数据
const startDate = ref(['2024', '09', '01'])
const endDate = ref(['2024', '09', '30'])

// 选择器选项
const dataTypeOptions = ref(['全部', '报关单', '舱单', '运单', '核注清单'])
const statusOptions = ref(['全部', '成功', '失败'])

// 页面加载
onMounted(() => {
  // 设置默认日期范围（最近30天）
  const today = new Date()
  const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)

  searchForm.endDate = today.toISOString().split('T')[0]
  searchForm.startDate = thirtyDaysAgo.toISOString().split('T')[0]

  loadOverview()
  loadData()
  loadDataTypes()
})

// 加载统计概览
const loadOverview = async () => {
  try {
    const params = {
      startDate: searchForm.startDate || undefined,
      endDate: searchForm.endDate || undefined
    }
    const response = await storageStatisticsApi.getOverview(params)
    overview.value = response.data
  } catch (error) {
    console.error('加载统计概览失败:', error)
  }
}

// 加载数据类型
const loadDataTypes = async () => {
  try {
    const response = await storageStatisticsApi.getDataTypes()
    dataTypeOptions.value = ['全部', ...response.data]
  } catch (error) {
    console.error('加载数据类型失败:', error)
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.startDate = ''
  searchForm.endDate = ''
  searchForm.dataType = ''
  searchForm.storageStatus = ''

  // 重新加载数据
  finished.value = false
  pageNo.value = 1
  list.value = []
  loadData()
  loadOverview()
}

// 加载数据
const loadData = async () => {
  if (loading.value) return

  loading.value = true
  try {
    const params = {
      pageNo: pageNo.value,
      pageSize,
      startDate: searchForm.startDate || undefined,
      endDate: searchForm.endDate || undefined,
      dataType: searchForm.dataType === '全部' ? undefined : searchForm.dataType,
      storageStatus: searchForm.storageStatus === '全部' ? undefined :
                    (searchForm.storageStatus === '成功' ? 'SUCCESS' :
                     searchForm.storageStatus === '失败' ? 'FAILED' : undefined)
    }

    const response = await storageStatisticsApi.getPage(params)
    const newList = response.data.records

    if (pageNo.value === 1) {
      list.value = newList
    } else {
      list.value.push(...newList)
    }

    finished.value = newList.length < pageSize
    pageNo.value++
  } catch (error) {
    showToast('加载数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  finished.value = false
  pageNo.value = 1
  list.value = []
  loadData().finally(() => {
    refreshing.value = false
  })
  loadOverview()
}

// 上拉加载
const onLoad = () => {
  loadData()
}

// 日期确认
const onStartDateConfirm = (value) => {
  searchForm.startDate = `${value[0]}-${value[1].padStart(2, '0')}-${value[2].padStart(2, '0')}`
  showStartDatePicker.value = false
}

const onEndDateConfirm = (value) => {
  searchForm.endDate = `${value[0]}-${value[1].padStart(2, '0')}-${value[2].padStart(2, '0')}`
  showEndDatePicker.value = false
}

// 数据类型确认
const onDataTypeConfirm = (value) => {
  searchForm.dataType = value.selectedOptions[0].text
  showDataTypePicker.value = false
}

// 状态确认
const onStatusConfirm = (value) => {
  searchForm.storageStatus = value.selectedOptions[0].text
  showStatusPicker.value = false
}

// 导出数据
const exportData = async () => {
  const loadingToast = showLoadingToast({
    message: '正在导出...',
    forbidClick: true,
  })

  try {
    const params = {
      startDate: searchForm.startDate || undefined,
      endDate: searchForm.endDate || undefined,
      dataType: searchForm.dataType === '全部' ? undefined : searchForm.dataType,
      storageStatus: searchForm.storageStatus === '全部' ? undefined :
                    (searchForm.storageStatus === '成功' ? 'SUCCESS' :
                     searchForm.storageStatus === '失败' ? 'FAILED' : undefined)
    }

    await storageStatisticsApi.exportData(params)
    showToast('导出成功')
  } catch (error) {
    showToast('导出失败: ' + error.message)
  } finally {
    closeToast()
  }
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}
</script>

<style scoped>
.storage-statistics {
  background-color: #f7f8fa;
  min-height: 100vh;
}
</style>
